package top.software.service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import top.software.mapper.SavedFileMapper;
import top.software.mapper.UserMapper;
import top.software.pojo.SavedFile;
import top.software.pojo.User;
import top.software.util.Message;
import top.software.util.MessageUtil;

/**
 * @ClassName: FileService
 * @Author: Amosen
 * @Since: 2021/4/23
 */

@Service
public class FileService {

	@Autowired
	private SavedFileMapper fileMapper;

	@Autowired
	private UserMapper userMapper;

	public String fileLocation = "D:/software/uploadfiles/";

	private String[] pictureTypes = { ".jpg", ".png", ".jpeg", ".ico" };

	private String[] pdfTypes = { ".pdf" };

	private String[] bookTypes = { ".txt", ".mobi" };

	private String[] videoTypes = { ".mp4" };

	private String[] officeTypes = { ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx" };

	private String getFileType(String fileName) {
		String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		for (String pictureType : pictureTypes) {
			if (fileType.equalsIgnoreCase(pictureType)) {
				return "图片资源";
			}
		}

		for (String pdfType : pdfTypes) {
			if (fileType.equalsIgnoreCase(pdfType)) {
				return "PDF文档";
			}
		}

		for (String bookType : bookTypes) {
			if (fileType.equalsIgnoreCase(bookType)) {
				return "图书资源";
			}
		}

		for (String videoType : videoTypes) {
			if (fileType.equalsIgnoreCase(videoType)) {
				return "视频资源";
			}
		}

		for (String officeType : officeTypes) {
			if (fileType.equalsIgnoreCase(officeType)) {
				return "Office资源";
			}
		}
		return "未知资源";
	}

	public Message uploadFile(HttpServletRequest request, String uploader, int downloadAuth,
			MultipartFile[] multipartFiles) {
		// 创建本地目录
		File localFileHome = new File(fileLocation);
		if (!localFileHome.isDirectory()) {
			localFileHome.mkdirs();
		}

		for (MultipartFile multipartFile : multipartFiles) {
			try {
				// 生成本地文件保存路径
				String originFileName = multipartFile.getOriginalFilename();
				String localFilePath = fileLocation + uploader + originFileName;

				// 保存到本地
				multipartFile.transferTo(new File(localFilePath));

				// 生成数据库保存对象
				String fileType = getFileType(originFileName);
				long fileSize = multipartFile.getSize();
				SavedFile savedFile = new SavedFile(originFileName, localFilePath, fileType, fileSize, uploader, 0,
						downloadAuth);
				// 保存数据库记录
				fileMapper.addSavedFile(savedFile);
			} catch (Exception e) {
				return MessageUtil.uploadFail();
			}

		}
		return MessageUtil.success();
	}

	public Message getAllFile() {
		List<SavedFile> savedFiles = fileMapper.getAllFile();
		return MessageUtil.success().addData("files", savedFiles);
	}

	private SavedFile checkQualification(int userAuth, int fileId) {
		SavedFile savedFile = fileMapper.getFileById(fileId);
		if (savedFile == null) {
			return null;
		} else {
			int fileAuth = savedFile.getDownloadAuth();
			if (fileAuth == UserService.COMMON_USER) {
				return savedFile;
			} else {
				if (fileAuth == UserService.MANAGER && userAuth == UserService.COMMON_USER) {
					return null;
				} else if (fileAuth == UserService.ROOT
						&& (userAuth == UserService.COMMON_USER || userAuth == UserService.MANAGER)) {
					return null;
				}
				return savedFile;
			}
		}
	}

	public Message downloadFile(String loginAccount, Integer fileId, HttpServletResponse response) {
		User savedUser = userMapper.getUserByAccount(loginAccount);
		SavedFile savedFile = null;
		if (savedUser == null) {
			return MessageUtil.lowAuth();
		} else {
			savedFile = checkQualification(savedUser.getAuth(), fileId);
			if (savedFile == null) {
				return MessageUtil.lowAuth();
			}
		}
		String filePath = savedFile.getFilePath();
		doDownload(filePath, response);
		return null;
	}

	private void doDownload(String filePath, HttpServletResponse response) {
		if (filePath != null && response != null) {
			File file = new File(filePath);
			if (file.exists()) {
				byte[] buffer = new byte[1024];

				FileInputStream fis = null;
				BufferedInputStream bis = null;

				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					ServletOutputStream out = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						out.write(buffer, 0, i);
						i = bis.read(buffer);
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				} finally {
					if (fis != null) {
						try {
							fis.close();
						} catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
						}
					}
					if (bis != null) {
						try {
							bis.close();
						} catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

}
